package com.itheima.bigevent.controller;

import com.itheima.bigevent.pojo.Result;
import com.itheima.bigevent.pojo.User;
import com.itheima.bigevent.service.UserService;
import com.itheima.bigevent.utils.JwtUtil;
import com.itheima.bigevent.utils.Md5Util;
import com.itheima.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 注册接口
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/register")
    public Result register(@Pattern(message = "用户名只能是5至16位的非空字符", regexp = "^\\S{5,16}$") String username, @Pattern(message = "密码只能是5至16位的非空字符", regexp = "^\\S{5,16}$") String password) {
        if (userService.register(username, password)) {
            return Result.success();
        } else {
            return Result.error("注册失败，请换个用户名试试");
        }
    }

    /**
     * 登陆接口
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public Result login(@Pattern(message = "用户名只能是5至16位的非空字符", regexp = "^\\S{5,16}$") String username, @Pattern(message = "密码只能是5至16位的非空字符", regexp = "^\\S{5,16}$") String password) {
        // 根据用户名查询User
        User user = userService.findByUsername(username);

        // 判断是否查询到
        if (user != null && user.getId() != null) {
            // 判断密码是否正确
            if (Md5Util.checkPassword(password, user.getPassword())) {
                // 生成token
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", user.getId());
                claims.put("username", user.getUsername());
                String token = JwtUtil.genToken(claims);

                // 将token存储在Redis中，并设置过期时间
                stringRedisTemplate.opsForValue().set(JwtUtil.TOKEN_REDIS_PREFIX + user.getUsername(), token, JwtUtil.EXPIRE_TIME, TimeUnit.SECONDS);

                return Result.success(token);
            } else {
                return Result.error("密码错误");
            }
        } else {
            return Result.error("用户不存在");
        }
    }

    /**
     * 获取当前用户信息
     *
     * @return 当前用户信息
     */
    @RequestMapping("/userinfo")
    public Result<User> userInfo() {
        User currentUser = ThreadLocalUtil.get();
        String username = currentUser.getUsername();

        // 从数据库获取最新的用户信息
        currentUser = this.userService.findByUsername(username);
        // 将最新的用户信息写回ThreadLocal中
        ThreadLocalUtil.set(currentUser);

        return Result.success(currentUser);
    }

    /**
     * 更新用户信息
     *
     * @param user 需要更新的用户信息
     * @return 成功或失败
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated(User.Update.class) User user) {
        userService.update(user);
        return Result.success();
    }

    /**
     * 更新用户头像地址
     *
     * @param avatarUrl 用户上传的头像在OSS中的地址
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 修改用户密码
     *
     * @param params 前端传过来的参数
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody @NotNull @Size(min = 3, max = 3, message = "参数不正确") Map<String, String> params, @RequestHeader(JwtUtil.HEADER_TOKEN_NAME) String token) {
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }

        if (!newPwd.equals(rePwd)) {
            return Result.error("新密码与确认密码不一致");
        }

        // 获取用户当前密码
        User currentUser = ThreadLocalUtil.get();
        currentUser = userService.findByUsername(currentUser.getUsername());
        ThreadLocalUtil.set(currentUser);

        if (!Md5Util.checkPassword(oldPwd, currentUser.getPassword())) {
            return Result.error("原密码不正确");
        }

        userService.updatePwd(newPwd);

        // 删除redis中之前记录的token
        stringRedisTemplate.opsForValue().getOperations().delete(JwtUtil.TOKEN_REDIS_PREFIX + currentUser.getUsername());

        return Result.success();
    }
}
